<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="行业名称" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入行业名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" plain icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['fieldType:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['fieldType:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['fieldType:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['fieldType:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="FieldTypeList" @selection-change="handleSelectionChange" row-key="id" lazy :load="loadChildren" :tree-props="{children: 'childrenList', hasChildren: 'exitSon'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />

      <el-table-column label="行业名称" align="center" prop="fieldName" />
      <el-table-column label="父类名称" align="center" prop="systemCatalogName" >
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.systemCatalogId">{{scope.row.parentName}}</span>-->
<!--          <span v-else>—</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="目录类型" align="center" prop="systemCatalogName" ></el-table-column>
      <el-table-column label="对应关键词" align="center" prop="keyWords" ></el-table-column>
      <el-table-column label="分类排序" align="center" prop="sort"/>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['fieldType:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['fieldType:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="handleSetting(scope.row)" v-hasPermi="['fieldType:remove']">设置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改引擎信息信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="行业名称" prop="fieldName">
          <el-input v-model="form.fieldName" placeholder="请输入行业名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入行业名称排列顺序" type="number"/>
        </el-form-item>
        <el-form-item label="父类名称" prop="parentName">
          <el-cascader
            :props="parentProps"
            ref="cascader"
            filterable
            clearable
            :show-all-levels="false"
            :collapse-tags="true"
            v-model="form.systemCatalogId"
          ></el-cascader>
<!--          <el-cascader :options="options"  clearable v-model.number="form.systemCatalogId" @change="handleChange">-->
<!--          </el-cascader>-->
        </el-form-item>
        <el-form-item label="对应关键词" prop="keyWords">
          <el-input v-model="form.keyWords" placeholder="请输入对应关键词" />
        </el-form-item>
        <!-- <el-form-item label="关键词" prop="keyWords">
          <el-tag v-for="(tag,index) in keywords" :key="index" closable :disable-transitions="false" @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Keyword</el-button>
        </el-form-item> -->
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
        <!--    设置用户可见的对话框-->
    <el-dialog title="门户分类信息可见设置" :visible.sync="settingOpen" width="500px">
      <el-form :model="form">
        <el-form-item label="用户级别" :label-width="formLabelWidth">
          <el-select v-model="settingForm.userLevel" placeholder="请选择用户级别" multiple filterable >
            <el-option  v-for="userLevel in userLevels" :key="userLevel.value" :label="userLevel.label" :value="userLevel.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型" :label-width="formLabelWidth" multiple filterable >
          <el-select v-model="settingForm.userType" placeholder="请选择用户类型" multiple>
            <el-option v-for="userType in userTypes" :key="userType.value" :label="userType.label" :value="userType.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指定用户" :label-width="formLabelWidth">
          <el-select v-model="settingForm.specificUser" placeholder="请选择指定用户" multiple>
            <el-option v-for="user in specifiedUsers" :key="user.value" :label="user.label" :value="user.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="settingOpen = false">取 消</el-button>
        <el-button type="primary" @click="settingOpen = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFieldType,
  getFieldType,
  delFieldType,
  addFieldType,
  updateFieldType,
  listAllFieldType,
} from "@/api/qysj/app/FieldType.js";

export default {
  name: "FieldType",
  data() {
    return {
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fieldNames:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 引擎信息信息表格数据
      FieldTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      settingOpen:false,
      //对话框宽度
      formLabelWidth:'80px',
      // 对话框表单设置
      settingForm:{
        userLevel:[],
        userType:[],
        specificUser:[]
      },
      // 模拟用户类型，用户级别，指定用户数据
      userLevels: [
        { label: '初级', value: 'primary' },
        { label: '中级', value: 'middle' },
        { label: '高级', value: 'senior' },
        // Add more options as needed
      ],
      userTypes: [
        { label: '个人', value: 'type1' },
        { label: '企业', value: 'type2' },
        { label: '政府人员', value: 'type3' },
        // Add more options as needed
      ],
      specifiedUsers: [
        { label: '张三', value: 'user1' },
        { label: '李四', value: 'user2' },
        { label: '王麻子', value: 'user3' },
        { label: 'zcl', value: 'user4' },
        { label: '张欣悦', value: 'user5' },
        // Add more options as needed
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        catalogTypes:'0,1,2'
      },
      // 表单参数
      form: {},
      parentProps: {
        lazy: true,
        multiple: false,
        clearable: true,
        emitPath: false,
        checkStrictly:true,
        lazyLoad(node, resolve) {
          console.log('node', node)
          if (node.root){
            const nodes=[
              {
                value:10000,
                label:'门户目录体系',
                leaf:false
              },
              {
                value:10001,
                label:'管理目录体系',
                leaf:false
              }
            ]
            resolve(nodes)
          }else {
            listFieldType({
              keyword: null,
              parentId: (node.value === 10001 || node.value === 10000) ? 0 : node.value,
              systemCatalogId:  (node.value === 10001 || node.value === 10000) ?  node.value :node.systemCatalogId,
              catalogTypes: '0,1,2'
            }).then(res => {
              if (res.code === 200) {
                const nodes = res.rows.map(item => {
                  return {
                    value: item.id,
                    label: item.fieldName ,
                    leaf: !item.exitSon
                  }
                });
                resolve(nodes)
              }
            })
          }
        }
      },
      keywords:[],
      inputVisible: false,
      inputValue: '',
      // 表单校验
      rules: {
        auditId: [
          { required: true, message: "审核Id不能为空", trigger: "blur" },
        ],
        createUserId: [
          { required: true, message: "创建用户ID不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    /** 查询信息信息列表 */
    getList() {
      this.loading = true;
      listFieldType(this.queryParams).then((response) => {
        console.log('1',response)
        this.FieldTypeList = response.rows.map(row => ({
          ...row,
          keyWords: this.formatKeywords(row.keyWords) // 格式化关键词
        }));
        this.total = response.total;
        this.loading = false;
      });
    },

    // 格式化关键词，去除开头和结尾逗号并分割为数组
    formatKeywords(keywords) {
      if (!keywords) return [];
      keywords = keywords.trim(); // 去除首尾空格
      if (keywords.startsWith(",")) {
        keywords = keywords.substring(1); // 去除开头逗号
      }
      if (keywords.endsWith(",")) {
        keywords = keywords.substring(0, keywords.length - 1); // 去除结尾逗号
      }
      return keywords.split(",");
    },
    //加载节点子级
    loadChildren(tree, treeNode, resolve){
      let Params = {
        pageNum: 1,
        pageSize: 30,
        parentId:tree.id
      }
      listFieldType(Params).then((response) => {
        resolve(response.rows);
      });

    },
    getOptions() {
      listAllFieldType(this.queryParams).then((res) => {
        function bl(arr) {
          let newArr = [];
          if(arr && arr.length>0){
            arr.forEach((obj) => {
            let newa = {};
            newa.label = obj.name;
            newa.value = obj.id;
            newa.parentId = obj.parentId;
            if (obj.childrenList && obj.childrenList.length > 0) {
              newa.children = bl(obj.childrenList);
              newArr.push(newa);
            } else {
              newa.children = null;
              newArr.push(newa);
            }
          });
          }
          return newArr;
        }
        // this.options = bl(res.data);
      });

    },
    handleChange(val){
      console.log('val', val)
      if(val.length == 1){
        this.form.systemCatalogId = val[val.length-1];
      }else{
        this.form.parentId = val[val.length-1];
      }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        auditId: null,
        startTime: null,
        endTime: null,
        name: null,
        createUserId: null,
        type: null,
        unit: null,
        price: null,
        remark: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        parentId: "0",
        typeValue: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.fieldNames = selection.map((item) => item.fieldName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分类信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getFieldType(id).then((response) => {
        this.form = response.data;

        this.open = true;
        this.title = "修改分类信息";
      });
    },
    handleClose(tag) {
        this.keywords.splice(this.keywords.indexOf(tag), 1);
      },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.keywords.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let parames = JSON.parse(JSON.stringify(this.form));
          parames.typeValue = 0;
          // console.log(this.keyWords)
          // parames.keywordList = this.keyWords;
          if(parames.keyWords && parames.keyWords.length>0){
            parames.keyWords.replace(/，/g,",")//中英文逗号
            parames.keywordList = parames.keyWords.split(",");
          }
          if (this.form.id != null) {
            if (!parames.parentId) { parames.parentId = 0; parames.parentName = ""};
            updateFieldType(parames).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getOptions();
            });
          } else {
            if (!parames.parentId) { parames.parentId = 0; parames.parentName = ""};
            addFieldType(parames).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getOptions();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const fieldNames=row.fieldName || this.fieldNames
      console.log(ids);
      this.$modal
        .confirm('是否确认删除行业名称为"' + row.fieldName + '"的数据项？')
        .then(function () {
          return delFieldType(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
     // 设置按钮操作
    handleSetting(row){
      this.settingOpen=true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "fieldType/export",
        {
          ...this.queryParams,
        },
        `FieldType_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
